<template>
  <div class="edit">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{title}}</span>
        <el-button @click="$router.go(-1)" style="float: right; padding: 3px 0" type="text">返回</el-button>
      </div>
      <el-form ref="form" :model="form" label-width="140px">
        <el-form-item label="商品选择">
          <el-button @click="chooseGoods" type="primary" size="mini">{{goodsInfo?'重新':''}}选择</el-button>
        </el-form-item>

        <!-- 商品信息 -->
        <div v-if="goodsInfo" class="goods">
          <div class="item">
            <span>产品编号</span>
            <span>{{goodsInfo.goodsNumber}}</span>
          </div>
          <div class="item">
            <span>产品封面图</span>
            <span>
              <el-image
                class="image"
                fit="cover"
                :src="goodsInfo.goodsCover[0]"
                :preview-src-list="goodsInfo.goodsCover"
              ></el-image>
            </span>
          </div>

          <div class="item">
            <span>产品名称</span>
            <span>{{goodsInfo.goodsName}}</span>
          </div>

          <div class="item">
            <span>产品价格</span>
            <span
              class="price-desc"
              v-for="(item,index) in goodsInfo.activityGoodsStandard"
              :key="index"
            >{{item.goodsDesc}}</span>
          </div>
        </div>

        <el-form-item v-if="goodsInfo" label="商品模式" prop="activityType">
          <el-radio-group v-model="form.activityType" @change="activityTypeChange">
            <el-radio :label="1">限时抢购</el-radio>
            <el-radio :label="2">拼团</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 限时抢购 -->
        <div v-if="goodsInfo && form.activityType === 1">
          <el-form-item label="活动有效期" prop="activityTime">
            <el-date-picker
              v-model="form.activityTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="活动价格设置" prop="panicBuyDiscountModel">
            <el-radio-group v-model="form.panicBuyDiscountModel">
              <el-radio :label="1">固定价格</el-radio>
              <el-radio :label="2">折扣比例(%)</el-radio>
            </el-radio-group>
          </el-form-item>

          <div v-if="form.panicBuyDiscountModel === 1 && goodsInfo">
            <el-form-item
              v-for="(item,index) in goodsInfo.activityGoodsStandard"
              :key="index"
              prop="price"
            >
              <div class="sub">
                <span>{{item.goodsPriceDesc}}</span>
                <el-input-number
                  v-model="item.fixedPrice"
                  controls-position="right"
                  :min="0"
                  placeholder="请输入优惠后的价格"
                ></el-input-number>
              </div>
            </el-form-item>
          </div>
          <div v-if="form.panicBuyDiscountModel === 2 && goodsInfo">
            <el-form-item v-for="(item,index) in goodsInfo.activityGoodsStandard" :key="index">
              <div class="sub">
                <span>{{item.goodsPriceDesc}}</span>
                <el-input-number v-model="item.scale" controls-position="right" :min="1" :max="100"></el-input-number>
                <el-button
                  class="realPrice"
                  type="text"
                >{{((item.price * (item.scale || 100)) / 100).toFixed(2)}}元</el-button>
              </div>
            </el-form-item>
          </div>
        </div>

        <!-- 拼团 -->
        <div v-if="goodsInfo && form.activityType === 2">
          <el-form-item label="拼团有效期" prop="activityTime">
            <el-date-picker
              v-model="form.activityTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="拼团人数上限" prop="groupBuyMax">
            <el-input-number
              v-model="form.groupBuyMax"
              controls-position="right"
              :min="1"
              :max="10"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="拼团返现金额" prop="newsDesc">
            <el-form-item
              class="price-item"
              v-for="(item,index) in goodsInfo.activityGoodsStandard"
              :key="index"
            >
              <div class="sub">
                <span>{{item.goodsPriceDesc}}</span>
                <el-input class="input" v-model="item.returnMoney" placeholder="请输入拼团返现金额"></el-input>
              </div>
            </el-form-item>
          </el-form-item>

          <el-form-item label="被邀请者拼团价格" prop="newsDesc">
            <el-form-item
              class="price-item"
              v-for="(item,index) in goodsInfo.activityGoodsStandard"
              :key="index"
            >
              <div class="sub">
                <span>{{item.goodsPriceDesc}}</span>
                <el-input class="input" v-model="item.groupPrice" placeholder="请输入被邀请者拼团价格"></el-input>
              </div>
            </el-form-item>
          </el-form-item>
          <el-form-item label="拼团规则文案" prop="groupBuyDesc">
            <Editor v-model="form.groupBuyDesc" />
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">重置</el-button>
        </el-form-item>
      </el-form>

      <el-dialog
        title="选择商品(点击行即可选择)"
        :visible.sync="openChooseGoods"
        width="1200px"
        append-to-body
      >
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="80px"
        >
          <el-form-item label="产品名称" prop="goodsName">
            <el-input
              v-model="queryParams.goodsName"
              placeholder="请输入产品名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table
          v-loading="loading"
          :data="goodsList"
          highlight-current-row
          @current-change="handleCurrentChange"
          ref="singleTable"
        >
          <el-table-column label="产品编号" align="center" prop="goodsNumber" />
          <el-table-column label="产品封面" align="center" prop="goodsCover">
            <template slot-scope="scope">
              <el-image
                style="width:40px;height:40px"
                fit="cover"
                :src="scope.row.goodsCover[0]"
                :preview-src-list="scope.row.goodsCover"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center" prop="goodsName" />
          <el-table-column label="产品价格" align="center" prop="goodsMoneyMin">
            <template slot-scope="scope">
              <span>{{scope.row.goodsMoneyMin}}元~{{scope.row.goodsMoneyMax}}元</span>
            </template>
          </el-table-column>
          <el-table-column label="产品状态" align="center" prop="goodsStatus">
            <template slot-scope="scope">
              <span>{{scope.row.goodsStatus | filterGoodsStatus}}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" />
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getGoodsList"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="sureChooseGoods">确定</el-button>
          <el-button @click="cancelChooseGoods">取消</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import Editor from "@/components/Editor";
import Upload from "@/components/Upload";
import {
  getActivity,
  addActivity,
  updateActivity
} from "@/api/system/activity";
import { listGoods } from "@/api/system/goods";

export default {
  name: "ActivityEdit",
  components: {
    Editor,
    Upload
  },
  filters: {
    filterGoodsStatus(value) {
      return {
        1: "正常",
        2: "限时抢购",
        3: "拼团",
        4: "下架"
      }[value];
    }
  },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      title: "添加活动",
      goodsInfo: null, // 展示选择的商品详情
      currentRow: null, // 选择的商品
      openChooseGoods: false,
      // 总条数
      total: 0,
      // 产品表格数据
      goodsList: [],
      loading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null
      },

      // 表单参数
      form: {
        activityType: 1, // 1-限时抢购,2-拼团
        activityTime: "",
        panicBuyDiscountModel: 1, // 1=固定价格 2=折扣比例
        groupBuyMax: "", // 团购人数上限,
        groupBuyDesc: "" // 团购文案
      }
    };
  },
  mounted() {
    this.getEditInfo();
    this.getGoodsList();
  },
  methods: {
    activityTypeChange(val) {
      if (val === 2) {
        document.body.scrollIntoView();
      }
    },
    handleCurrentChange(val) {
      this.currentRow = {
        ...val,
        goodsId: val.id
      };
      delete this.currentRow.id;
    },

    sureChooseGoods() {
      if (!this.currentRow) {
        this.msgError("请选择商品");
        return;
      }
      let activityGoodsStandard = JSON.parse(this.currentRow.goodsStandard);
      activityGoodsStandard = activityGoodsStandard.map(item => {
        return {
          ...item,
          goodsDesc: `${item.desc} ${item.price}元 `,
          goodsPriceDesc: `${item.desc}
          原价：${item.price}元 `,
          fixedPrice: item.price, // 固定-优惠金额
          discountsPrice: 0, // 折扣比例-优惠金额
          scale: 100, // 折扣比例
          returnMoney: 0, // 拼团返现金额
          groupPrice: item.price //被邀请者拼团价格
        };
      });
      this.goodsInfo = {
        ...this.currentRow,
        goodsId: this.currentRow.goodsId,
        activityGoodsStandard
      };

      this.openChooseGoods = false;
    },
    cancelChooseGoods() {
      this.currentRow = null;
      this.goodsInfo = null;
      this.openChooseGoods = false;
      this.$refs.singleTable.setCurrentRow(null);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getGoodsList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询产品列表 */
    getGoodsList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows.map(item => {
          item.goodsCover = item.goodsCover.split(",");
          return item;
        });

        this.total = response.total;
        this.loading = false;
      });
    },
    chooseGoods() {
      this.openChooseGoods = true;
    },

    getEditInfo() {
      const id = this.$route.query.id;
      if (id) {
        getActivity(id).then(response => {
          this.form = {
            ...response.data,
            activityTime: [
              new Date(response.data.activityStart),
              new Date(response.data.activityEnd)
            ]
          };
          this.goodsInfo = {
            ...response.data,
            ...response.data.goods,
            activityGoodsStandard: JSON.parse(
              response.data.activityGoodsStandard
            ),
            id,
            goodsCover: response.data.goods.goodsCover.split(",")
          };
          this.currentRow = this.form.goods;
          this.$nextTick(() => {
            document.body.scrollIntoView();
          });
        });
        this.title = "修改活动";
      }
    },

    /** 提交按钮 */
    submitForm() {
      if (!this.currentRow) {
        this.msgError("请选择商品");
        return;
      }

      if (!this.form.activityTime) {
        this.msgError(
          `请选择${this.form.activityType === 1 ? "活动有效期" : "拼团有效期"}`
        );
        return;
      }
      const activityGoodsStandard = this.goodsInfo.activityGoodsStandard.map(
        item => {
          item.discountsPrice = +(
            (item.price * (item.scale || 100)) /
            100
          ).toFixed(2);
          return item;
        }
      );
      const postData = {
        ...this.goodsInfo,
        ...this.form,
        activityGoodsStandard: JSON.stringify(activityGoodsStandard),
        activityStart: this.filterDate(this.form.activityTime[0]),
        activityEnd: this.filterDate(this.form.activityTime[1]),
        groupBuyDesc: this.filterContent(this.form.groupBuyDesc),
        goodsAgreement: this.filterContent(this.form.goodsAgreement),
        goodsContent: this.filterContent(this.form.goodsContent),
        goods: {
          ...this.form.goods,
          goodsAgreement: this.filterContent(this.form.goodsAgreement),
          goodsContent: this.filterContent(this.form.goodsContent)
        },
        activityStatus: 0
      };

      if (postData.id != null) {
        updateActivity(postData).then(response => {
          if (response.code === 200) {
            this.msgSuccess("修改成功");
            this.$router.go(-1);
          }
        });
      } else {
        addActivity(postData).then(response => {
          if (response.code === 200) {
            this.msgSuccess("添加成功");
            this.$router.go(-1);
          }
        });
      }
    },
    // 重置按钮
    cancel() {
      this.getEditInfo();
      this.resetForm("form");
    }
  }
};
</script>
<style lang="scss" scoped>
.goods {
  background: #eee;
  margin-left: 140px;
  margin-bottom: 20px;
}
.item {
  font-size: 14px;
  padding: 18px 0;
  span:first-child {
    width: 100px;
    display: inline-block;
    text-align: right;
  }
  span:last-child {
    margin-left: 20px;
    display: inline-block;
  }
  .image {
    width: 40px;
    height: 40px;
  }
}

.sub {
  display: flex;
  span {
    display: inline-block;
    width: 200px;
    text-align: right;
    padding-right: 20px;
  }
  .input {
    width: 300px;
  }
  .realPrice {
    margin-left: 20px;
  }
}
.price-item {
  margin-bottom: 20px;
}
.price-desc {
  display: inline-block;
  margin-left: 20px;
}
</style>
